package com.coocaa.app.support.net.monitor;

import com.alibaba.fastjson.JSONObject;
import com.coocaa.app.support.net.HttpServiceManager;
import com.coocaa.app.support.thread.CCThread;

import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import retrofit2.Response;

public class DefaultMonitorImpl implements HttpServiceManager.HttpServiceMonitor {
    private static final Executor executor = Executors.newSingleThreadExecutor(CCThread.newThreadFactory("default-http-monitor"));
    private static final DefaultMonitorHttpServiceManager monitor = new DefaultMonitorHttpServiceManager(null);

    @Override
    public void submit(final String method, final Map<String, String> headers, final int httpCode, final int errCode, final String errMsg, final long duration) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                String params = "";
                if (headers != null)
                    params = JSONObject.toJSONString(headers);
                try {
                    Response<String> response = monitor.submit(method, params, httpCode, errCode, errMsg, duration).execute();
                    if (response != null) {
                        int code = response.code();
                        if (!(code >= 200 && code < 400))
                            Thread.sleep(30 * 1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
